package com.calvin.study.strategy.spring.context;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.calvin.study.strategy.strategy.Strategy;

//策略上下文，用于管理策略的注册和获取
//Spring优化为Bean，实例化该Bean时将实现了Strategy接口的Bean注册到策略表中（registerMap）
@Component
public class StrategyContext implements InitializingBean {

	@Autowired
	private ApplicationContext applicationContext;

	private static Map<String, Strategy> registerMap = new HashMap<>();

	// 注册策略
	public static void registerStrategy(String rewardType, Strategy strategy) {
		registerMap.putIfAbsent(rewardType, strategy);
	}

	// 获取策略
	public static Strategy getStrategy(String rewardType) {
		return registerMap.get(rewardType);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		registerMap = applicationContext.getBeansOfType(Strategy.class);
		System.out.println(registerMap);
	}
}
